package com.imooc.controller;


import com.imooc.pojo.MyConfig;
import com.imooc.pojo.Stu;
import com.imooc.pojo.Student;
import com.imooc.utils.JSONResult;
import com.imooc.utils.MyAsyncTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

//@Controller
@RestController
@Slf4j
public class HelloController {
    @RequestMapping("hello")
//    @ResponseBody
    public String hello() {
        return "Hello IMOOC!~";
    }

    @Autowired
    private Stu stu;

    @GetMapping("getStu")
    public Object getStu() {
        return stu;
    }

    @Autowired
    private MyConfig myConfig;
    // 注入异步任务
    @Autowired
    private MyAsyncTask myAsyncTask;

    @GetMapping("getMyConfig")
    public Object getMyConfig() {
        myAsyncTask.publishMsg();
        log.info("这是跳过异步任务的执行");
        return myConfig;
    }

    // 从application.yml中获取配置属性
    @Value("${self.custom.config.sdkSecret}")
    private String sdkSecret;
    @Value("${self.custom.config.host}")
    private String host;
    @Value("${self.custom.config.port}")
    private String port;
    @Value("${app.name.xxx.yyy.zzz}")
    private String xyz;
    // 做输出
    @GetMapping("getYmlCustomConfig")
    public Object getYmlCustomConfig() {
        return sdkSecret + ";\t" + host + ":" + port + ";\t" + xyz;
    }

    @GetMapping("getStudent")
    public JSONResult getStudent() {    // 将返回值由Object改为JSONResult
        Student stu = new Student();
        stu.setName("imooc");
        stu.setAge(18);

//        System.out.println(stu);  // 打印日志方式比较原始

        Student stu2 = new Student("风间影月",20);
        // 打印日志
        log.debug(stu.toString());
        log.info(stu.toString());
        log.warn(stu.toString());
        log.error(stu.toString());

//        return JSONResult.errorMsg("调用接口错误");
        return JSONResult.ok(stu);

    }

    // 文件上传
    @PostMapping("upload")
    public String upload(MultipartFile file) throws Exception {
        file.transferTo(new File("E:\\imooc\\SpringBoot 2.× 手把手零基础入门与进阶\\imooc-springboot-starter\\temp\\" + file.getOriginalFilename()));  // 保存文件
        return "上传成功";
    }
}
